package com.lq.learningTest.duoxiancheng;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchTest {

    public static void main(String[] args) throws InterruptedException {

        ExecutorService pool = Executors.newCachedThreadPool();
        CountDownLatch countDownLatch = new CountDownLatch(3);

        Runnable task1 = () -> {
            ThreadUtils.sleep(new Random().nextInt(5000));
            System.out.println("计算山西分公司的账目");
            countDownLatch.countDown();//每执行一次，就会减一
        };
        Runnable task2 = () -> {
            ThreadUtils.sleep(new Random().nextInt(5000));
            System.out.println("计算北京分公司的账目");
            countDownLatch.countDown();
        };
        Runnable task3 = () -> {
            ThreadUtils.sleep(new Random().nextInt(5000));
            System.out.println("计算上海分公司的账目");
            countDownLatch.countDown();
        };
        pool.submit(task1);
        pool.submit(task2);
        pool.submit(task3);
        countDownLatch.await();//直到把countDown减为0才会执行下面的代码
        System.out.println("计算总账！");

    }
}
